// file:src/include/os/file.h
// autor:jiangxinpeng
// time:2021.2.23
// copyright:(C) by jiangxinpeng,All right are reserved.

#ifndef OS_FILE_H
#define OS_FILE_H

#include <os/fsal.h>

#define FSAL_FILE_MAX 10

#define FSAL_FILE_FREE 0
#define FSAL_FILE_USING 1

// max open file number
#define FSAL_FILE_OPEN_MAX 128

// bad file idx
#define FSAL_FILE_BAD_IDX(idx) ((idx) < 0 || (idx) > FSAL_FILE_OPEN_MAX)
// bad file point
#define FSAL_FILE_BAD_FILE(fp) (!(fp) || !(fp)->fsal || !(fp)->flags)

#define FSAL_FILE_IDX2FILE(idx) (fsal_file_table + idx)
#define FSAL_FILE_FILE2IDX(file) (((file)-fsal_file_table))

typedef struct
{
    atomic_t ref;
    int flags;
    fsal_t *fsal;
    int handle;
    void *extension;
} fsal_file_t;

extern fsal_file_t *fsal_file_table;

int FsalFileTableInit();
fsal_file_t *FsalFileAlloc();
int FsalFileFree(fsal_file_t *fsal_file);

static int FsalFileIncRef(fsal_file_t *file)
{
    AtomicInc(&file->ref);
}

static int FsalFileDecRef(fsal_file_t *file)
{
    if (AtomicGet(&file->ref) > 0)
        AtomicDec(&file->ref);
}

static int FsalFileNeedClose(fsal_file_t *file)
{
    return AtomicGet(&file->ref) > 0;
}

#endif